<template>
  <div class="flex flex-direction-c formItem">
    <div class="formlabel">
      <template v-if="value.placeholer">
        <a-tooltip placement="right">
          <template #title>
            <span>{{ value.placeholer }}</span>
          </template>
          <span class="highlight"> {{ value.label }}: </span>
        </a-tooltip>
      </template>
      <template v-else> {{ value.label }}: </template>

      <template v-if="answer">
        <a-tag color="pink">{{ answer }}</a-tag></template
      >
    </div>
    <template v-if="value.inputType && value.inputType == 'textarea'">
      <a-textarea
        size="large"
        v-model:value="value.value"
        @change="ErrorString()"
      />
    </template>
    <template v-else>
      <a-input
        size="large"
        v-model:value="value.value"
        @change="ErrorString()"
      />
    </template>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, PropType, reactive } from "vue";
import { cloneDeep } from "lodash";
import { componentFrom } from "@/type";
import { is_phone,is_url } from "@/lib/is";

export default defineComponent({
  name: "fromis",
  props: {
    valueArray: {
      type: Object as PropType<componentFrom>,
      required: true,
    },
  },

  setup(props, context) {
    // const value: componentFrom = cloneDeep(props.valueArray) as componentFrom;
    const value: componentFrom = reactive(props.valueArray as componentFrom);
    //初始化父组件

    const answer = ref<string>("");

    const ErrorString = () => {
      let result = true;
      switch (value.type) {
        case "require":
          if (value.value == null || value.value == "") {
            answer.value = "不能为空";
            result = false;
          }
          break;
        case "phoneNumberRequire":
          var arr = value.value.split("\n");
          arr.map((item) => {
            if (!is_phone(item)) {
              answer.value = "并不是电话的格式";
              result = false;
            }
          });
          break;
        case "urlRequire":
          if (!is_url(value.value)) {
            answer.value = "并不是正常网站的格式";
            result = false;
          }
          break;
      }
      value.status = result;
      if (result) answer.value = "";
      context.emit("test", value.status);
      return;
    };
    //初始化
    ErrorString();

    return {
      answer,
      value,
      ErrorString,
    };
    // console.log(props.valueArray);

    // value = props.valueArray as DataItem;
    // console.log(value);
  },
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.highlight {
  color: #42b983;
}
.formlabel {
  margin-bottom: 5px;
  display: flex;
  justify-content: space-between;
}
</style>
